package com.active.web;

import com.active.dao.entity.ActIdGroup;
import com.active.dao.entity.ActIdUser;
import com.active.dao.mapper.ActIdGroupMapper;
import com.active.dao.mapper.ActIdUserMapper;
import com.active.service.AjaxPageResult;
import com.active.service.util.CreateNoteId;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.*;
import org.activiti.engine.history.HistoricDetail;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.identity.Group;
import org.activiti.engine.identity.User;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.DeploymentBuilder;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.*;
import java.util.zip.ZipInputStream;

/**
 * Created by Administrator on 2019/6/3 0003.
 */

@RestController
@Slf4j
@RequestMapping("createMarket")
public class CreateMarketController {

    @Resource(name = "taskService")
    private TaskService taskService;

    @Resource(name = "runtimeService")
    private RuntimeService runtimeService;

    @Resource(name = "repositoryService")
    private RepositoryService repositoryService;

    @Resource(name = "identityService")
    private IdentityService identityService;

    @Resource(name = "historyService")
    private HistoryService historyService;

    @Resource(name = "formService")
    private FormService formService;

    @Autowired
    private ActIdUserMapper actIdUserMapper;

    @Autowired
    private ActIdGroupMapper actIdGroupMapper;

    @RequestMapping("action")
    public AjaxPageResult action(){
        //指定流程实例
//        Deployment builder = repositoryService.createDeployment().addClasspathResource("UserAndGroup.bpmn").name("taincai").deploy();
//
//
//
//        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionId("myProcess_1")
//
//
//        runtimeService.startProcessInstanceByKey("流程");
//        TaskQuery taskQuery = processEngine.getTaskService().createTaskQuery();
//        taskQuery.active();

        // 获取流程定义key, 和最新的流程id

        List<ActIdUser> users1 = actIdUserMapper.list();

        List<ActIdGroup> groups2 = actIdGroupMapper.list();


//        创建用户
        User user = identityService.newUser(CreateNoteId.getGuid());
        user.setFirstName("li");
        user.setLastName("yunlong");
        user.setEmail("1007060032@qq.com");
        user.setPassword("liyunlong");
        identityService.saveUser(user);
        //创建用户
        User user2 = identityService.newUser(CreateNoteId.getGuid());
        user2.setFirstName("zhao");
        user2.setLastName("gang");
        user2.setEmail("1156653905@qq.com");
        user2.setPassword("zhaogang");
        identityService.saveUser(user2);

        //创建用户
        User user3 = identityService.newUser(CreateNoteId.getGuid());
        user3.setFirstName("tian");
        user3.setLastName("yu");
        user3.setEmail("115653905@qq.com");
        user3.setPassword("tianyu");
        identityService.saveUser(user3);

        User user4 = identityService.newUser(CreateNoteId.getGuid());
        user4.setFirstName("duan");
        user4.setLastName("peng");
        user4.setEmail("115605@qq.com");
        user4.setPassword("duanpeng");
        identityService.saveUser(user4);

        User user5 = identityService.newUser(CreateNoteId.getGuid());
        user5.setFirstName("chu");
        user5.setLastName("yunfei");
        user5.setEmail("11560125@qq.com");
        user5.setPassword("chuyunfei");
        identityService.saveUser(user5);

        User user6 = identityService.newUser(CreateNoteId.getGuid());
        user6.setFirstName("xiu");
        user6.setLastName("qin");
        user6.setEmail("1156023125@qq.com");
        user6.setPassword("xiuqin");
        identityService.saveUser(user6);

        Group group = identityService.newGroup(CreateNoteId.getGuid());
        group.setName("部门领导");
        group.setType("assignment");//security-role  两种type


        Group group1 = identityService.newGroup(CreateNoteId.getGuid());
        group1.setName("狼人");
        group1.setType("assignment");//security-role  两种type


        identityService.saveGroup(group);
        identityService.saveGroup(group1);

        //建立关系

        List<ActIdUser> users = actIdUserMapper.list();

        List<ActIdGroup> groups = actIdGroupMapper.list();



        for(int i=0;i<users.size();i++){

            if(i<3){
                identityService.createMembership(users.get(i).getId(),groups.get(0).getId());
            }else {
                identityService.createMembership(users.get(i).getId(),groups.get(1).getId());
            }
        }



//        List<User> list = identityService.createUserQuery().memberOfGroup("dulituan").list();
////        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionId();
//
//
//        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("UserAndGroup");
//
//        Task tasks = taskService.createTaskQuery().taskCandidateUser("zhaogang").singleResult();
//        taskService.claim(tasks.getId(),"zhaogang");
//        Task task = taskService.createTaskQuery().taskCandidateUser("liyunlong").singleResult();





//        BpmnModel bpmnModel = repositoryService.getBpmnModel(processInstance.getProcessDefinitionId());
//        Collection<FlowElement> lstFlowElement = ProcessUtil.getProcesAllTaskCanvas(bpmnModel);
//
//        TaskQuery taskQuery = taskService.createTaskQuery();
//
//        List<ProcessTaskDO> lstProcessTaskPo = new ArrayList<ProcessTaskDO>();
//        List<FlowDO> lstFlow = new ArrayList<FlowDO>();
//        // 记录每一个流程操作信息
//        for (FlowElement flowElement : lstFlowElement) {
//            String taskType = flowElement.getClass().getSimpleName();
//            String taskKey = flowElement.getId();
//            String taskName = flowElement.getName();
////            if (processTaskType.contains(taskType)) {
////                ProcessTaskDO processTaskPo = new ProcessTaskDO(processDefinitionId, processDefinitionKey,
////                        taskKey, taskName, taskType, processName, proceeVersion);
////                lstProcessTaskPo.add(processTaskPo);
////                // 记录流程进入的信息
////                List<SequenceFlow> lstInSequenceFlow = ((FlowNode) flowElement).getIncomingFlows();
////                for (SequenceFlow sf : lstInSequenceFlow) {
////                    lstFlow.add(new FlowDO(sf.getId(), sf.getName(), sf.getSourceRef(), sf.getTargetRef(),
////                            sf.getConditionExpression(), sf.getSkipExpression(), FlowDO.FLOW_IN,
////                            processDefinitionId, processDefinitionKey, taskKey, taskType, processName,
////                            proceeVersion, sf.getDocumentation()));
////                }
////                // 记录流程出的信息
////                List<SequenceFlow> lstOutSequenceFlow = ((FlowNode) flowElement).getOutgoingFlows();
////                for (SequenceFlow sf : lstOutSequenceFlow) {
////                    lstFlow.add(new FlowDO(sf.getId(), sf.getName(), sf.getSourceRef(), sf.getTargetRef(),
////                            sf.getConditionExpression(), sf.getSkipExpression(), FlowDO.FLOW_OUT,
////                            processDefinitionId, processDefinitionKey, taskKey, taskType, processName,
////                            proceeVersion, sf.getDocumentation()));
////                }
////            }
//        }

        return AjaxPageResult.success("创建用户成功");
    }

    public void queryProImg(String processInstanceId) throws Exception {
        //获取历史流程实例
        HistoricProcessInstance processInstance =  historyService.createHistoricProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();

        //根据流程定义获取输入流
        InputStream is = repositoryService.getProcessDiagram(processInstance.getProcessDefinitionId());
        BufferedImage bi = ImageIO.read(is);
        File file = new File("F:/datatest/active/src/main/resources/xx.png");
        if(!file.exists()) file.createNewFile();
        FileOutputStream fos = new FileOutputStream(file);
        ImageIO.write(bi, "png", fos);
        fos.close();
        is.close();
        System.out.println("图片生成成功");
    }


    //已有自动部署，该代码注释掉
    //单个部署打开,单个部署是相对路径，大爷的
    @RequestMapping("deploy")
    public AjaxPageResult deploy(){
        //部署流程，只需要部署一次，不然会报错（待解决），可以另起项目用来部署，把需要部署的文件
        //打包发到服务器，直接读取服务器上面的.bpmn文件，此处只是本地测试

        String URL = "diagrams/leaveSign.bpmn";

        DeploymentBuilder builder = repositoryService.createDeployment().addClasspathResource(URL);
        builder.name("单个部署1").deploy();

        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionKey("leaveSign").singleResult();

        return AjaxPageResult.success("单个部署成功：{}",processDefinition.getId());
    }


    @RequestMapping("apply")
    public AjaxPageResult apply(String name){

        //设置当前申请人
        identityService.setAuthenticatedUserId(name);
        //启动流程
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionKey("leavetest").singleResult();

        Map<String,String> map = new HashMap<>();
        map.put("reason","想去世界走一走");
        map.put("startDate","2019-06-10");
        map.put("reson","2019-06-10");
        map.put("endDate","2019-06-10");

        ProcessInstance processInstance = formService.submitStartFormData(processDefinition.getId(),map);

        return AjaxPageResult.success("流程申请成功");

    }

    @RequestMapping("leaderAudit")
    public AjaxPageResult leaderAudit(String value,String user){
        //指定流程实例
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionKey("leavetest").singleResult();


        //存在需要同一个领导处理多个任务情况，这里支取一条，具体的根据业务逻辑来处理
        List<Task> task = taskService.createTaskQuery().taskAssignee(user).list();



        if (null == task || task.size() == 0){
            return AjaxPageResult.fail("该处理人没有任务审批:"+user);
        }

        //取最后的一条作为需要处理的任务
        Task task1 = task.get(task.size()-1);

        Map<String,String> map = new HashMap<>();
        map.put("startDate","2019-06-10");
        map.put("reson","2019-06-10");
        map.put("reason","长得帅");
        map.put("endDate","2019-06-10");
        if(user.equals("liyunlong")){
            map.put("leaderApprove",value);
        }else {
            map.put("hrApprove",value);
        }

//        ProcessInstance processInstance = formService.submitStartFormData(processDefinition.getId(),map);

        formService.submitTaskFormData(task1.getId(),map);

        //验证流程是否已经结束
        HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery().
                processInstanceId(processDefinition.getId()).finished().singleResult();

        if(null == historicProcessInstance){
            return AjaxPageResult.success("流程未结束,流程审批成功");
        }

        //流程结束，读取数据
        List<HistoricDetail> list = historyService.createHistoricDetailQuery().processInstanceId(processDefinition.getId()).list();

        return AjaxPageResult.success("流程结束，读取历史数据：{}",list);

    }

    @RequestMapping("check")
    public AjaxPageResult check(){
        //指定流程实例
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionKey("leavetest").singleResult();

        //验证流程是否已经结束
        HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery().
                processInstanceId(processDefinition.getId()).finished().singleResult();

        if(null == historicProcessInstance){
            return AjaxPageResult.success("流程未结束,流程审批成功");
        }

        //流程结束，读取数据
        List<HistoricDetail> list = historyService.createHistoricDetailQuery().processInstanceId(processDefinition.getId()).list();

        return AjaxPageResult.success("流程结束，读取历史数据：{}",list);


    }

}
